package thread;

//自己实现一个阻塞队列
class MyBlockingQueue{
    private String[] data = null;

    //队首
    private int head = 0;
    //队尾
    private  int tail = 0;
    //元素个数
    private int val = 0;

    public MyBlockingQueue(int capacity){
        data = new String[capacity];
    }

    //入队
    public void put(String elem){
        synchronized (this){
            if (val >= data.length){
                //队列满了，需要阻塞
                return;
            }
            data[tail] = elem;
            tail++;
            if (tail >= data.length){
                tail = 0;
            }
            //也可以用
            //tail = (tail +1) % data.length;

            val ++;
        }
    }

    //出队
    public String take(){
        synchronized (this){
            if (val == 0){
                //队列空了，需要阻塞
                return null;
            }
            String ret = data[head];
            head++;
            if (head >= data.length){
                head = 0;
            }
            val--;
            return ret;
        }
    }

}

public class Demo32 {
    public static void main(String[] args) {

    }
}
